package com.kc.gb.device.plugins.strip;

import cn.hutool.core.io.FileUtil;
import com.kc.gb.base.dto.Result;
import com.kc.gb.base.dto.DeviceType;
import com.kc.gb.device.common.interfaces.IHardware;
import com.kc.gb.device.common.properties.DeviceProperties;
import com.kc.gb.device.plugins.strip.driver.AtopControl;
import com.kc.gb.device.plugins.strip.driver.AtopControlHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

@Slf4j
@Service("STRIP")
public class StripHardware implements IHardware {

    @Resource
    DeviceProperties deviceProperties;

    @Resource
    ThreadPoolTaskScheduler scheduledThreadPoolExecutor;

    private Result INITIALIZE_RESULT = Result.success();

    private AtopControl atopControl;

    @Override
    public DeviceType getDeviceType() {
        return DeviceType.STRIP;
    }

    @Override
    public boolean isEnabled() {
        return deviceProperties.isDeviceStripEnabled();
    }

    @Override
    public Result<?> isConnected() throws Exception {
        return INITIALIZE_RESULT;
    }

    @Override
    public boolean testConnect(String ip, int port) throws Exception {
        return false;
    }

    @Override
    public Result<?> initialize() throws Exception {
        String ip  = deviceProperties.getDeviceStripIP();
        int port = deviceProperties.getDeviceStripPort();
        atopControl = AtopControlHolder.getAtopControl(ip,port);
        return Result.success();
    }

    @Override
    public void afterInitialize(Result<?> result) throws Exception {
        this.INITIALIZE_RESULT = result;
    }

    public AtopControl getAtopControl() {
        return atopControl;
    }

    @Override
    public void stopConnect() {

    }

    public static String getRootPath(Class<?> clazz) {
        String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
        File root = new File(path);
        String rootPath = root.getParentFile().getPath();
        if (rootPath.endsWith("target")) {
            rootPath = rootPath + File.separator + "classes";
        }
        log.info("light control##rootPath=" + rootPath);
        return rootPath;
    }

    private void writeIpIndexFile(Class<?> clazz,String ip,String port,String deviceId) throws IOException {
        String filePath = getRootPath(clazz);
        log.info("light control##IPINDEX filePath:{}", filePath);
        File file = new File(filePath, "IPINDEX");
        if (!file.exists()) {
            file.createNewFile();
        }
        String deviceData = deviceId + " " + port + " " + ip;
        FileUtil.writeLines(Arrays.asList(deviceData), file, Charset.defaultCharset());
    }
}
